<?php
namespace app\pay\controller;
use think\Input;
class Pay extends Common{
    public function initialize(){
        parent::initialize(); 
    }  
    // 接收订单
    public function index($channelid='',$money='',$shopid='',$appid='',$orderid_out='',$paytype='',$note='',$returnurl='',$notifyurl='',$sign='',$version=''){ 
    	if(request()->isPost()){  
            // if(empty($note)){
            //     $result = ['code'=>-1,'msg'=>'请备注付款时所使用的微信/支付宝账号名称'];  
            //     return json($result);
            // }
            if(empty($channelid)||empty($money)||empty($shopid)||empty($appid)||empty($orderid_out)||empty($paytype)){
                $result = ['code'=>-1,'msg'=>'信息不完整！']; 
                return json($result);
            }
            $this->shop=db('shop')->where(array('id' =>$shopid,'appid' =>$appid,'open' =>1))->find();
            if($this->shop){   
                // 签名验证成功
                if($this->verify($orderid_out,$channelid,$paytype,$money,$returnurl,$notifyurl,$sign)){
                    $info=db('channel')->where('id',$channelid)->where('shopid',$shopid)->where('shopappid',$appid)->where('open',1)->find();
                    db('user_banks')->where('id',$paytype)->update(['lasttime'=>time()]);
                    // var_dump($info);die;
                    if($info){
                        $orderidnew=$channelid.'N'.rand_string(8,1).'S'.$shopid;
                        $data['orderid']=$orderidnew; 
                        $data['orderid_out']=$orderid_out;
                        $data['channelname']=$info['title'];
                        $data['channelid']=$info['id'];
                        $data['shopname']=$info['shopname'];
                        $data['shopid']=$info['shopid'];
                        $data['cionname']=$info['cionname'];
                        $data['cionid']=$info['cionid'];
                        $data['shopappid']=$info['shopappid'];
                        $data['userid']=$info['userid'];
                        $data['agentid']=$info['agentid'];
                        $data['price']=$info['price'];  
                        $data['money']=string2array($money);  
                        $data['number']=bcdiv($data['money'],$data['price'],6); 
                        if($data['number']>0) {
                            $data['number']=$data['money']/$data['price']; 
                            $data['number']=sprintf("%.6f",$data['number']);
                        }else{
                            $data['number']=bcdiv($data['money'],$data['price'],6); 
                        } 
                        $data['addtime']=time(); 
                        $data['bankid']=$paytype;
                        $data['state']=0;
                        $data['note']=$note;
                        // 其他
                        $data['sign']=$sign;
                        $data['returnurl']=$returnurl;
                        $data['notifyurl']=$notifyurl;
                        $data['version']=$version;
                        // 手续费
                        $bankty=db('user_banks')->where('id',$paytype)->value('name_en');
                        // $data['fei_user_lv']=$info['rate']; 
                        // $data['fei_user']=$info['rate']*$data['money']*0.01;
                        $feiuser_i=explode('|',$info['rate']);             
                        if($bankty==='Wxpay'){
                            $data['fei_user_lv']=$feiuser_i[0]; 
                            $data['fei_user']=$feiuser_i[0]*$data['money']*0.01;
                        }else if($bankty==='Alipay'){
                            $feiuserss=$feiuser_i[1]?$feiuser_i[1]:$feiuser_i[0];
                            $data['fei_user_lv']=$feiuserss; 
                            $data['fei_user']=$feiuserss*$data['money']*0.01;
                        }else if($bankty==='Bank'){
                            $feiusersss=$feiuser_i[2]?$feiuser_i[2]:$feiuser_i[0];
                            $data['fei_user_lv']=$feiusersss; 
                            $data['fei_user']=$feiusersss*$data['money']*0.01;
                        }  
                        $shopinfo=db('shop')->where('id',$info['shopid'])->find();
                        // $data['fei_shop_lv']=$shopinfo['lv']; 
                        // $data['fei_shop']=$shopinfo['lv']*$data['money']*0.01;
                        $feishop_i=explode('|',$shopinfo['lv']); 
                        if($bankty==='Wxpay'){
                            $data['fei_shop_lv']=$feishop_i[0]; 
                            $data['fei_shop']=$feishop_i[0]*$data['money']*0.01;
                        }else if($bankty==='Alipay'){
                            $feishopss=$feishop_i[1]?$feishop_i[1]:$feishop_i[0];
                            $data['fei_shop_lv']=$feishopss; 
                            $data['fei_shop']=$feishopss*$data['money']*0.01;
                        }else if($bankty==='Bank'){
                            $feishopsss=$feishop_i[2]?$feishop_i[2]:$feishop_i[0];
                            $data['fei_shop_lv']=$feishopsss; 
                            $data['fei_shop']=$feishopsss*$data['money']*0.01;
                        }  

                        if($info['agentid']){
                            $agentinfo=db('users')->where('id',$info['agentid'])->find();
                                // $data['fei_agent_lv']=$agentinfo['agentlv']; 
                                // $data['fei_agent']=$agentinfo['agentlv']*$data['money']*0.01;
                                $feiagent_i=explode('|',$agentinfo['agentlv']); 
                                if($bankty==='Wxpay'){
                                    $data['fei_agent_lv']=$feiagent_i[0]; 
                                    // $data['fei_agent']=$feiagent_i[0]*$data['money']*0.01;
                                    $data['fei_agent']=($feiagent_i[0]-$feiuser_i[0])*$data['money']*0.01;
                                }else if($bankty==='Alipay'){
                                    $feiagenss=$feiagent_i[1]?$feiagent_i[1]:$feiagent_i[0];
                                    $data['fei_agent_lv']=$feiagenss; 
                                    // $data['fei_agent']=$feiagenss*$data['money']*0.01;
                                    $data['fei_agent']=($feiagenss-$feiuser_i[1])*$data['money']*0.01;
                                }else if($bankty==='Bank'){
                                    $feiagensss=$feiagent_i[2]?$feiagent_i[2]:$feiagent_i[0];
                                    $data['fei_agent_lv']=$feiagensss; 
                                    // $data['fei_agent']=$feiagensss*$data['money']*0.01;
                                    $data['fei_agent']=($feiagensss-$feiuser_i[2])*$data['money']*0.01;
                                }   
                        }
                        $id = db('channel_order')->insertGetId($data);
                        if($id){  
                            $payurl=$this->sys['url'].url('pay/pay/gotopay',['orderid'=>$orderidnew,'appid'=>$appid,'sign'=>$sign]); 
                            // $result = ['code'=>1,'msg'=>'跳转支付……'];

                            header("Location:".$payurl);
                        }else{
                            $result = ['code'=>-1,'msg'=>'提交失败，请重试!'];
                        } 
                    }else{
                        $result = ['code'=>-1,'msg'=>'通道异常!'];
                    } 
                }else{
                    $result = ['code'=>-1,'msg'=>'签名错误!'];
                }                
            }else{ 
                $result = ['code'=>-1,'msg'=>'商户异常!'];
            } 
    	}
    	return json($result);
    } 
    // 验证签名
    protected function verify($orderid_out,$channelid,$paytype,$money,$returnurl='',$notifyurl='',$sign){
        //POST参数
        $requestarray = array(
            "orderid_out" =>$orderid_out, //商户订单号
            "appid" => $this->shop['appid'], //商户APPID 固定派发
            "shopid" => string2array($this->shop['id']), //商户ID 固定派发
            "channelid" => string2array($channelid), //通道ID 动态派发
            "paytype" => $paytype, //支付ID 动态派发
            "money" => $money, //订单金额
            "returnurl" => $returnurl, //跳转链接
            "notifyurl" => $notifyurl, //通知链接
            "version" => $this->sys['version'], //签名版本号 固定派发                    
        );         
        $Md5key        = $this->shop['appkey'];
        $md5keysignstr = $this->createSign($Md5key, $requestarray);
        if ($sign===$md5keysignstr) { 
            return true;
        } else { 
            return false;
        }
    }
    // 创建签名
    protected function createSign($Md5key,$requestarray){
        ksort($requestarray);
        $md5str = "";
        foreach ($requestarray as $key => $val) {
            if (!empty($val)) {
                $md5str = $md5str . $key . "=" . $val . "&";
            }
        }
        // $md5str = htmlspecialchars($md5str);
        $sign = strtoupper(md5($md5str . "key=" . $Md5key));
        return $sign;
    }  
    // 去支付
    public function gotopay($orderid='',$appid='',$sign=''){  
        if(request()->isPost()){ 
            $order=db('channel_order')->where('orderid',$orderid)->where('shopappid',$appid)->where('sign',$sign)->find();
            if($order['state']===0){
                if(db('channel_order')->where('orderid',$orderid)->where('shopappid',$appid)->update(['state'=>1,'paytime'=>time()])!==false){
                    db('channel')->where('id',$order['channelid'])->where('shopappid',$order['shopappid'])->setInc('money_total',$order['money']);   
                    $gotourl= $this->sys['url'].url('pay/view/orderview',['orderid'=>$orderid,'appid'=>$appid,'sign'=>$sign]);
                    $result = ['code'=>1,'msg'=>'支付成功……','callbackurl'=>$gotourl];   
                }else{
                    $result = ['code'=>-1,'msg'=>'系统繁忙，请稍后再试!','orderid'=>$order['orderid']];
                }
            }else{
                $result = ['code'=>-1,'msg'=>'该订单已经支付或取消!','orderid'=>$order['orderid']];
            } 
            if($result['code']===1){
                $this->emailnotice($appid,$order['userid'],$order['orderid'],$order['shopname'],$order['cionname'],$order['number'],$order['money'],$sign,$order['bankid'],$order['note']); 
            }
            return $result;
        }else{ 
            $order=db('channel_order')->alias('o')
                ->join(config('database.prefix') . 'user_banks ub', 'o.bankid = ub.id', 'left')
                ->field('o.*,ub.name,ub.bank_name,ub.name_en,ub.qrcode,ub.bank_no,ub.content')
                ->where('o.orderid',$orderid)->where('o.shopappid',$appid)->find(); 
            if($order['state']===0){ 
                $this->assign('order',$order);   
                return $this->fetch('index/pay');
            }else{
                $this->redirect('pay/view/orderview',['orderid'=>$orderid,'appid'=>$order['shopappid'],'sign'=>$order['sign']]);
            }   
            return json($result);
        }      
    }   
    // 邮件通知
    public function emailnotice($appid='',$userid='',$orderid='',$shopname='',$cionname='',$number='',$money='',$sign='',$bankid='',$note=''){ 
        $sender=db('users')->where('id',$userid)->value('email');
        $paytype=db('user_banks')->where('id',$bankid)->value('name');
        $checkurl=$this->sys['url'].url('pay/view/mailcheck',['appid'=>$appid,'orderid'=>$orderid,'userid'=>$userid,'sign'=>$sign]); 
        $content='<div style="width: 90%;max-width: 400px;height: 320px;background: #fff;border-radius: 5px;margin:0 auto;box-shadow: 0 6px 13px 0 rgba(0,0,0,.13);overflow: hidden;"><div style="position: relative;height: 42px;line-height: 42px;padding: 0 15px;border-bottom: 1px solid #f6f6f6;color: #333;border-radius: 2px 2px 0 0;font-size: 14px;">订单信息</div><div style="padding: 10px 15px;line-height: 24px;"><div style="height: 30px;line-height: 30px;font-size: 14px;"><span class="name">订单号：</span><span class="ordernum">'.$orderid.'</span></div><div style="height: 30px;line-height: 30px;font-size: 14px;"><span class="red">提示：请确认该订单是否已收到相应的款项。</span></div><div style="height: 30px;line-height: 30px;font-size: 14px;"><span class="name">支付金：</span> <span class="ordernum">'.$money.'</span><span class="name">元</span></div><div style="height: 30px;line-height: 30px;font-size: 14px;"><span class="name">产品名：</span> <span class="name">'.$cionname.'('.$number.'份)</span></div><div style="height: 30px;line-height: 30px;font-size: 14px;"><span class="name">商户名：</span> <span class="name">'.$shopname.'</span></div><div style="height: 30px;line-height: 30px;font-size: 14px;"><span class="name">备注账号：</span> <span class="name">'.$note.'('.$paytype.')</span></div><div class="paybot" style="padding-top:40px;"> <a href="'.$checkurl.'" target="_blank" style="color:#fff;  text-decoration: none;display:block;height: 38px;line-height: 38px;padding: 0 18px;background-color: #0cb46a;color: #fff;white-space: nowrap;text-align: center; font-size: 14px;border: none;border-radius: 2px;cursor: pointer;">如果已收到，点击确认订单</a></div></div></div> ';
        $send = send_email($sender, '新订单提醒【'.$orderid.'】', $content);
    }


    public function checkorder()
    {
  

    }
}  